//
//  OAuthViewController.swift
//  Weibo1
//
//  Created by apple on 15/12/28.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
///用户登陆控制器
class OAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    //MARK: 设置监听方法
    @objc private func close() {
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    ///自动填充用户名和密码  web 注入 （以代码的方式向web页面添加内容）
    @objc private func autoFill() {
    
        let js = "document.getElementById('userId').value = '792079345@qq.com';" +
        "document.getElementById('passwd').value = 'wuyz@4664';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
   //MARK: 设置界面
    override func loadView() {
        super.loadView()
        view = webView
        
        //设置代理
        webView.delegate = self
        
        view.backgroundColor = UIColor.whiteColor()
        
        //设置导航栏
        title = "登陆新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载界面
        self.webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
   
    }

}
//MARK:  UIWebViewDelegate
extension OAuthViewController: UIWebViewDelegate {

    ///将要加载请求的代理方法
     /// 如果 iOS 的代理方法中有返回 bool，通常返回 true 很正常，返回 false 不能正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //目标  如果是百度 就不加载 
        // 1 判断访问主机是否是 www.baidu.com
        guard let url = request.URL where url.host == "www.baidu.com" else {
        
            return true
        }
        // 2 从百度地址的url 中提取 “code= ” 是否存在
        guard let query = url.query where query.hasPrefix("code=") else {
        
            print("取消授权")
            return false
        }
        //3 从query 字符串只提取 “code=” 后面的授权码
        let code = query.substringFromIndex("code=".endIndex)
        
        print(query)
        
        print("授权码是" + code)
        
        //4 加载 accessToken
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
            //finished 的完整代码
            if isSuccessed {
            
                print("成功了")
                print(UserAccountViewModel.sharedUserAccount.account)
            }else {
            
                print("失败了")
                
            }
        }
        return false
  }
}